﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using ADNDNetwork;

namespace ADNDNetwork.Network.Server
{
    public class ServerManager
    {
        private Dictionary<int, Thread> listOfThreads;
        private Dictionary<int, Socket> listOfClientSocket;

        private Thread runGameThread;

        private string ip = string.Empty;
        private int port = int.MinValue;


        private byte[] buffer;
        private const int BUFFER_SIZE = 1024;

        AsyncCallback callback;


        public ServerManager(string ipAddress, int portNumber)
        {
            listOfClientSocket = new Dictionary<int, Socket>();            
            ip = ipAddress;
            port = portNumber;
            buffer = new byte[BUFFER_SIZE];
            

            callback = new AsyncCallback(readFromClient);
            runGameThread = new Thread(runGameServer);
        }

        public void runGame()
        {
            runGameThread.Start();
        }

        private void runGameServer()
        {
            TcpListener serverSocket = new TcpListener(IPAddress.Parse(ip), port);
            int requestCount = 0;
            TcpClient clientSocket = default(TcpClient);

            serverSocket.Start();

            Console.WriteLine(" >> Server Started. Waiting for connections.");

            clientSocket = serverSocket.AcceptTcpClient();

            //connect a stream to the client
            NetworkStream ns = clientSocket.GetStream();
            Console.WriteLine(" >> Accepted connection from client");

            while (true)
            {
                if (ns.DataAvailable)
                {
                    //DATA IS AVAILABLE
                    BinaryFormatter df = new BinaryFormatter();
                    Object obj = df.Deserialize(ns);
                    AdndMessage m = (AdndMessage)obj;

                    if (m.Body.ToUpper().Trim().Equals("EOG"))
                    {
                        System.Diagnostics.Debug.WriteLine("End of connection request received");
                        break;
                    }

                    System.Diagnostics.Debug.WriteLine("Server Echo: " + m.Body + Environment.NewLine);

                    m.Body = "Response from server: " + m.Body;
                    df.Serialize(ns, m);
                }

                Thread.Sleep(500);
            }

            ns.Close();
            clientSocket.Close();

            requestCount = 0;
        }

        static void readFromClient(IAsyncResult results)
        {
            //METHOD WAS CALLED BY THE DELEGATE
        }
    } 
}
